import React, { useEffect, useState, useRef } from 'react'
import { Button, Modal, Layout, Select, Cascader, Avatar, Space, message, Table, Input } from 'antd';
import { UserAddOutlined, EditTwoTone, DeleteTwoTone, ExclamationCircleOutlined } from '@ant-design/icons';
import { Routes, Route, useNavigate, Navigate } from 'react-router-dom'
import axios from 'axios';
import { screenHeight, screenWidth } from '../../../Constants'
import myprovinceData from '../../../js/provinceData';
import { isOwnEmpty } from '../../../js/isEmptyObjc';
const { confirm } = Modal;
const { Option } = Select;
const { Search } = Input;
const provinceData = myprovinceData;
export default function Index() {
  let editUserInfo = {}
  let addUserInfo = {}
  const navigate = useNavigate()
  const [originData, setOriginData] = useState(0);
  const [userList, setUserList] = useState(); //备份 originData
  const { Content, } = Layout;
  const [editvisible, seteditVisible] = useState(false);
  const [addvisible, setaddVisible] = useState(false);

  const [editUserid, setEditUserid] = useState('');

  const pwdRef = useRef();
  const nameRef = useRef();
  const addressRef = useRef();
  const phoneRef = useRef();
  const emailRef = useRef();

  const pwdRef2 = useRef();
  const nameRef2 = useRef();
  const addressRef2 = useRef();
  const phoneRef2 = useRef();
  const emailRef2 = useRef();

  useEffect(() => {
    message.destroy();
    axios.get("http://localhost:8080/getUserList").then(resp => {
      console.log('resp的内容:', resp);
      setUserList(resp.data.data)
      setOriginData(resp.data.data)
    }).catch(err => {
      console.log(err);
      message.error("请求失败!", 1)
    })
    return () => {
    
    };
  }, []);
  // record 当前行的数据
  const deleteUser = (record) => {
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: `确认要删除${record.nickname}吗?`,
      onOk() {
        console.log(record);
        axios.post("http://localhost:8080/deleteUser?id=" + record.id).then(resp => {
          if (resp.data.state === "0") {
            message.success(resp.data.message, 1);
           window.location.reload();
          } else {
            message.error(resp.data.message, 1)
          }
        }).catch(err => {
          message.error("网络超时!", 1)
        })
      },
    });
  }
  const columns = [
    {
      title: '昵称',
      dataIndex: 'nickname',
      ellipsis: true,
    },
    {
      title: '详细地址',
      dataIndex: 'address',
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      ellipsis: true,
    },
    {
      title: '邮箱号',
      dataIndex: 'email',
      ellipsis: true,
    },
    {
      title: 'Action',
      key: 'action',
      width: '15%',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={() => { showModal(record) }}>编辑<EditTwoTone /></a>
          {/*  record 当前行的数据 */}
          <a onClick={() => { deleteUser(record) }} style={{ marginLeft: 5 }}> 删除<DeleteTwoTone twoToneColor="red" /></a>
        </Space>
      ),
    },
  ];

  const showModal = (record) => {
    seteditVisible(true);
    // editUserInfo.id = record.id;
    setEditUserid(record.id)
    pwdRef.current.state.value = '';
    nameRef.current.state.value = '';
    addressRef.current.state.value = '';
    phoneRef.current.state.value = '';
    emailRef.current.state.value = '';
  };
  const showModal2 = () => {
    setaddVisible(true);
    addUserInfo.id = record.id;
    pwdRef2.current.state.value = '';
    nameRef2.current.state.value = '';
    addressRef2.current.state.value = '';
    phoneRef2.current.state.value = '';
    emailRef2.current.state.value = '';
  };

  const handleOk = () => {
    editUserInfo.password = pwdRef.current.state.value || null;
    editUserInfo.nickname = nameRef.current.state.value || null;
    editUserInfo.address = addressRef.current.state.value || null;
    editUserInfo.phone = phoneRef.current.state.value || null;
    editUserInfo.email = emailRef.current.state.value || null;
    console.log(editUserInfo);
    console.log("修改后是否是个空对象:",isOwnEmpty(editUserInfo));
    if (isOwnEmpty(editUserInfo)) {
      seteditVisible(false);
      return 
    }
    editUserInfo.id = editUserid
    console.log("该用户修改后信息:", editUserInfo);
    const emailreg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    const phonereg = /^1[3|4|5|7|8]\d{9}$/
    const pwdReg = /^[a-zA-Z0-9]{6,18}$/;
    if (editUserInfo.email!=null ) {
      if (!emailreg.test(editUserInfo.email)) {
        message.error("邮箱格式错误!", 1)
        seteditVisible(false);
        return 
      }
    } 
    if (editUserInfo.phone!=null) {
      if (!phonereg.test(editUserInfo.phone)) {
        message.error("手机格式错误!", 1)
        seteditVisible(false);
        return 
      }
    }
    if(editUserInfo.password!=null){
      if (!pwdReg.test(editUserInfo.password)) {
        message.error("密码为6-18位包含数字字母的组合!");
        seteditVisible(false);
        return
      }
    }

    axios.post("http://localhost:8080/editUser", editUserInfo).then(resp => {
      if (resp.data.state === "0") {
        message.success(resp.data.message, 1)
        seteditVisible(false);
        setTimeout(() => {
          window.location.reload()
        }, 500);

      } else {
        message.error(resp.data.message, 1)
      }

    }).catch(err => {
      message.error("请求超时!", 1);
    })

  };


  const handleOk2 = () => {
    addUserInfo.password = pwdRef2.current.state.value || '123456';
    addUserInfo.nickname = nameRef2.current.state.value || "新用户";
    addUserInfo.address = addressRef2.current.state.value || null;
    addUserInfo.phone = phoneRef2.current.state.value || null;
    addUserInfo.email = emailRef2.current.state.value || null;
    console.log("添加的用户的信息:", addUserInfo);
    const emailreg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    const pwdReg = /^[a-zA-Z0-9]{6,18}$/;
    const phonereg = /^1[3|4|5|7|8]\d{9}$/
    if(addUserInfo.phone ==null ||addUserInfo.phone ==""){
      message.error("请输入手机号",1);
      return

    }
    if (addUserInfo.phone!=null && phonereg.test(addUserInfo.phone)) {
    } else {
        message.error("手机格式错误!", 1)
        return 
    }
    if(addUserInfo.email ==null ||addUserInfo.email ==""){
      message.error("请输入电子邮箱",1);
      return
      
    }
    if (addUserInfo.email!=null && emailreg.test(addUserInfo.email)) {
    } else {
        message.error("邮箱格式错误!", 1)
        return 
    }
    if(addUserInfo.password!="" &&addUserInfo.password!="123456"&&addUserInfo.password!=null){
      if (!pwdReg.test(addUserInfo.password)) {
        message.error("密码为6-18位包含数字字母的组合!");
        return
      }
    }

    
   
    

    axios.post("http://localhost:8080/addUser", addUserInfo).then(resp => {
      if (resp.data.state === "0") {
        message.success(resp.data.message, 1)
        seteditVisible(false);
        window.location.reload()
      } else {
        message.error(resp.data.message, 1)
        seteditVisible(false);
      }

    }).catch(err => {
      message.error("请求超时!", 1);
      seteditVisible(false);
    })

  };
  const genderSelect = (value) => {
    editUserInfo.gender = value;
  }
  const genderSelect2 = (value) => {
    addUserInfo.gender = value;
  }
  const citySelect = (value) => {
    editUserInfo.city = value;
  }
  const citySelect2 = (value) => {
    addUserInfo.city = value;
  }
  const handleCancel = () => {
    seteditVisible(false);
    editUserInfo = {}
  };

  const handleCancel2 = () => {
    setaddVisible(false);
    addUserInfo = {}
  };
  const onSearch = (value) => {
    console.log(value);
    let rs = [];
    rs = originData.filter((item, index) => {
      console.log(item);
      return item?.nickname.indexOf(value) != -1
    })
    console.log(rs);
    setOriginData(rs)
    if (value == null || value == "") {
      setOriginData(userList)
    }

  }
  const renderTableHead = () => {
    return (
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span>成员管理</span>
        <Space>
          <Search placeholder="搜索昵称" onSearch={onSearch} allowClear style={{ width: 200 }} />
          <Button type="primary" icon={<UserAddOutlined />} onClick={showModal2}>添加用户</Button>
        </Space>
      </div>

    )
  }
  return (
    <Content style={{ minHeight: 285 }} className="animate__animated animate__fadeIn">
      <Table columns={columns} dataSource={originData} bordered title={renderTableHead}
        pagination={{
          pageSize: 8,
        }}
      />
      <Modal
        title="编辑用户"
        visible={editvisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={'40%'}
        centered={true}
      >
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>密码</span><Input style={{ width: screenWidth * 0.2 }} ref={pwdRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>昵称</span><Input style={{ width: screenWidth * 0.2 }} ref={nameRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>详细地址</span><Input style={{ width: screenWidth * 0.2 }} ref={addressRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>手机</span><Input style={{ width: screenWidth * 0.2 }} ref={phoneRef} maxLength={11}/><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>电子邮箱</span><Input style={{ width: screenWidth * 0.2 }} ref={emailRef} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>城市</span><Cascader style={{ width: screenWidth * 0.2 }} onChange={citySelect} options={provinceData} defaultValue={''} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>性别</span>
          <Select placeholder="性别" defaultValue='' onSelect={genderSelect}>
            <Option value="0">男</Option>
            <Option value="1">女</Option>
            <Option value="2">保密</Option>
          </Select> <br /></p>
      </Modal>
      <Modal
        title="新增用户"
        visible={addvisible}
        onOk={handleOk2}
        onCancel={handleCancel2}
        width={'40%'}
        centered={true}
      >
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>密码</span><Input style={{ width: screenWidth * 0.2 }} ref={pwdRef2} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>昵称</span><Input style={{ width: screenWidth * 0.2 }} ref={nameRef2} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>详细地址</span><Input style={{ width: screenWidth * 0.2 }} ref={addressRef2} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>手机</span><Input style={{ width: screenWidth * 0.2 }} ref={phoneRef2} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>电子邮箱</span><Input style={{ width: screenWidth * 0.2 }} ref={emailRef2} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>城市</span><Cascader style={{ width: screenWidth * 0.2 }} onChange={citySelect2} options={provinceData} defaultValue={''} /><br /></p>
        <p style={{ display: 'flex' }}><span style={{ margin: 10, width: 70 }}>性别</span>
          <Select placeholder="性别" defaultValue='' onSelect={genderSelect2}>
            <Option value="0">男</Option>
            <Option value="1">女</Option>
            <Option value="2">保密</Option>
          </Select> <br /></p>
      </Modal>
    </Content>
  )

}
